<!--
 * @Author: Mr · Lei
 * @Date: 2024-10-18 14:33:11
 * @LastEditors: OBKoro1
 * @LastEditTime: 2024-10-18 14:33:12
 * @FilePath: \ruituan-tuan-web\src\views\nfc\nfc-config\components\userConfig.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by 四川开局红科技有限公司, All Rights Reserved. 
-->
<template>
  <a-row>
    <a-col :flex="1">
      <a-form
        :model="formModel"
        :label-col-props="{ span: 4 }"
        :wrapper-col-props="{ span: 18 }"
        label-align="left"
      >
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              field="user.nickname"
              :label="$t('nfcOrderList.form.config.user.nickname')"
              label-col-flex="80px"
            >
              <a-input
                v-model="formModel['user.nickname']"
                :placeholder="
                  $t('nfcOrderList.form.config.user.nickname.placeholder')
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              field="user.mobile"
              :label="$t('nfcOrderList.form.config.user.mobile')"
              label-col-flex="80px"
            >
              <a-input
                v-model="formModel['user.mobile']"
                :placeholder="
                  $t('nfcOrderList.form.config.user.mobile.placeholder')
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              field="rate"
              :label="$t('nfcOrderList.form.config.rate')"
              label-col-flex="80px"
            >
              <a-input
                v-model="formModel.rate"
                :placeholder="$t('nfcOrderList.form.config.rate.placeholder')"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              field="shop.name"
              :label="$t('nfcOrderList.form.config.shop.name')"
              label-col-flex="80px"
            >
              <a-input
                v-model="formModel['shop.name']"
                :placeholder="$t('nfcOrderList.form.config.min.placeholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              field="shop.address"
              :label="$t('nfcOrderList.form.config.shop.address')"
              label-col-flex="80px"
            >
              <a-input
                v-model="formModel['shop.address']"
                :placeholder="
                  $t('nfcOrderList.form.config.shop.address.placeholder')
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              field="createtime"
              :label="$t('nfcOrderList.form.createtime')"
              label-col-flex="80px"
            >
              <a-range-picker @change="changeDate" @clear="clearDate" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-col>
    <a-divider style="height: 84px" direction="vertical" />
    <a-col :flex="'86px'" style="text-align: right">
      <a-space direction="vertical" :size="18">
        <a-button type="primary" @click="search">
          <template #icon>
            <icon-search />
          </template>
          {{ $t('nfcOrderList.form.search') }}
        </a-button>
        <a-button @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          {{ $t('nfcOrderList.form.reset') }}
        </a-button>
      </a-space>
    </a-col>
  </a-row>
  <a-divider style="margin-top: 0" />
  <a-row style="margin-bottom: 16px">
    <a-col :span="12">
      <a-space>
        <a-button type="primary" @click="handleClickadd(0, {})">
          <template #icon>
            <icon-plus />
          </template>
          {{ $t('giftpack.table.operation.create') }}
        </a-button>
      </a-space>
    </a-col>
    <a-col
      :span="12"
      style="display: flex; align-items: center; justify-content: end"
    >
      <a-tooltip :content="$t('nfcOrderList.actions.refresh')">
        <div class="action-icon" @click="search"
          ><icon-refresh size="18"
        /></div>
      </a-tooltip>
      <a-dropdown @select="handleSelectDensity">
        <a-tooltip :content="$t('nfcOrderList.actions.density')">
          <div class="action-icon"><icon-line-height size="18" /></div>
        </a-tooltip>
        <template #content>
          <a-doption
            v-for="item in densityList"
            :key="item.value"
            :value="item.value"
            :class="{ active: item.value === size }"
          >
            <span>{{ item.name }}</span>
          </a-doption>
        </template>
      </a-dropdown>
      <a-tooltip :content="$t('nfcOrderList.actions.columnSetting')">
        <a-popover
          trigger="click"
          position="bl"
          @popup-visible-change="popupVisibleChange"
        >
          <div class="action-icon"><icon-settings size="18" /></div>
          <template #content>
            <div id="tableSetting">
              <div
                v-for="(item, index) in showColumns"
                :key="item.dataIndex"
                class="setting"
              >
                <div style="margin-right: 4px; cursor: move">
                  <icon-drag-arrow />
                </div>
                <div>
                  <a-checkbox
                    v-model="item.checked"
                    @change="
                      handleChange($event, item as TableColumnData, index)
                    "
                  >
                  </a-checkbox>
                </div>
                <div class="title">
                  {{ item.title === '#' ? '序列号' : item.title }}
                </div>
              </div>
            </div>
          </template>
        </a-popover>
      </a-tooltip>
    </a-col>
  </a-row>
  <a-divider style="margin-top: 0" />
  <a-table
    row-key="id"
    column-resizable
    :loading="loading"
    :pagination="pagination"
    :columns="(cloneColumns as TableColumnData[])"
    :data="InconeUserData"
    :bordered="{ wrapper: true, cell: true }"
    :size="size"
    @page-change="onPageChange"
  >
    <template #index="{ rowIndex }">
      {{ rowIndex + 1 + (pagination.page - 1) * pagination.limit }}
    </template>
    <template #logo="{ record }">
      <a-image width="50" height="50" :src="record.shop.logo" />
    </template>
    <template #avatar="{ record }">
      <a-image width="50" height="50" :src="record.user.avatar" />
    </template>
    <template #operations="{ record }">
      <a-space size="small">
        <a-button
          type="primary"
          size="mini"
          status="warning"
          @click="handleClickadd(1, record)"
        >
          <icon-edit />
          {{ $t('nfcOrderList.columns.operations.edit') }}
        </a-button>
        <a-popconfirm
          type="warning"
          :content="$t('nfcOrderList.columns.operations.delete.message')"
          @ok="handleDelete(record.id)"
        >
          <a-button type="primary" size="mini" status="danger">
            <icon-delete />
            {{ $t('nfcOrderList.columns.operations.delete') }}
          </a-button>
        </a-popconfirm>
      </a-space>
    </template>
  </a-table>
  <AddUserConfig :modal-obj="modalObj" @handle-cancel="handleCanceladd" />
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch, nextTick } from 'vue';
  import useLoading from '@/hooks/loading';
  import { Pagination } from '@/types/global';
  import {
    GetUserConfigListApi,
    DeleteUserConfigApi,
    PolicyParams,
  } from '@/api/nfc';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { useI18n } from 'vue-i18n';
  import { Message } from '@arco-design/web-vue';
  import Sortable from 'sortablejs';
  import cloneDeep from 'lodash/cloneDeep';
  import AddUserConfig from './adduser.vue';

  type Column = TableColumnData & { checked?: true };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  // 选项卡类型
  // 收益配置 列表
  const showColumns = ref<Column[]>([]);
  // 收益配置 分页属性
  const basePagination: Pagination = {
    page: 1,
    limit: 10,
    pageSize: 10,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 收益配置 搜索条件
  const generateFormModel = () => {
    return {
      'user.nickname': '',
      'user.mobile': '',
      'shop.name': '',
      'shop.address': '',
      'rate': '',
      'createtime': '',
    };
  };
  const generateFormModelOp = () => {
    return {
      'user.nickname': 'like',
      'user.mobile': 'like',
      'shop.name': 'like',
      'shop.address': 'like',
      'rate': '=',
      'createtime': 'BETWEEN',
    };
  };
  const cloneColumns = ref<Column[]>([]);
  const formModel = ref(generateFormModel());
  const formModelOp = ref(generateFormModelOp());
  // 人员配置 列表
  const InconeUserData = ref([]);
  const columns = computed<TableColumnData[]>(() => [
    {
      title: t('nfcOrderList.columns.index'),
      slotName: 'index',
      width: 80,
    },
    {
      title: t('nfcOrderList.columns.user.avatar'),
      dataIndex: 'shop.avatar',
      slotName: 'avatar',
      align: 'center',
    },
    {
      title: t('nfcOrderList.columns.user.nickname'),
      dataIndex: 'user.nickname',
      align: 'center',
    },
    {
      title: t('nfcOrderList.columns.user.mobile'),
      dataIndex: 'user.mobile',
      align: 'center',
    },
    {
      title: t('nfcOrderList.columns.shop.logo'),
      dataIndex: 'shop.logo',
      slotName: 'logo',
      align: 'center',
    },
    {
      title: t('nfcOrderList.columns.shop.name'),
      dataIndex: 'shop.name',
      align: 'center',
    },
    {
      title: t('nfcOrderList.columns.shop.address'),
      dataIndex: 'shop.address',
      align: 'center',
    },
    {
      title: t('nfcOrderList.columns.rate'),
      dataIndex: 'rate',
      align: 'center',
    },
    {
      title: t('nfcOrderList.columns.createtime'),
      dataIndex: 'createtime',
      align: 'center',
    },
    {
      title: t('nfcOrderList.columns.operations'),
      dataIndex: 'operations',
      slotName: 'operations',
      align: 'center',
      fixed: 'right',
      width: 200,
    },
  ]);
  // 接口请求 人员配置
  const GetUserConfigList = async (
    params: PolicyParams = { page: 1, limit: 10 }
  ) => {
    setLoading(true);
    try {
      const { data } = await GetUserConfigListApi(params);
      InconeUserData.value = data.data;
      pagination.page = params.page;
      pagination.total = data.total;
    } catch (err) {
      console.log(err);
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 转换选择的日期为时间戳
  const changeDate = (even: any) => {
    const starDate = (new Date(even[0]).getTime() / 1000).toString();
    const endDate = (new Date(even[1]).getTime() / 1000).toString();
    formModel.value.createtime = `${starDate},${endDate}`;
  };
  // 查询收益配置列表
  const search = () => {
    GetUserConfigList({
      ...basePagination,
      filter: JSON.stringify(formModel.value),
      op: JSON.stringify(formModelOp.value),
    });
  };
  search();
  // 查询收益配置列表 分页查询
  const onPageChange = (page: number) => {
    basePagination.page = page;
    search();
  };
  // 查询收益配置列表 重置查询
  const reset = () => {
    formModel.value = generateFormModel();
    basePagination.page = 1;
    search();
  };
  // 清除选择的日期
  const clearDate = () => {
    basePagination.page = 1;
    search();
  };
  // 定义弹窗对象
  const modalObj = reactive<any>({
    isVisible: false,
    type: 0,
    obj: {},
  });
  // 打开弹窗口
  const handleClickadd = (type: number, item?: any) => {
    modalObj.type = type;
    modalObj.obj = item;
    modalObj.isVisible = true;
  };

  const handleCanceladd = () => {
    modalObj.isVisible = false;
    search();
  };
  // 删除收益配置
  const handleDelete = async (ids: number) => {
    try {
      await DeleteUserConfigApi({ ids });
      Message.success(t('Message.deleteSuccess'));
      search();
    } catch (err) {
      console.log(err);
    }
  };

  // 表格列配置
  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const size = ref<SizeProps>('medium');

  // 定义尺寸
  const densityList = computed(() => [
    {
      name: t('nfcOrderList.size.mini'),
      value: 'mini',
    },
    {
      name: t('nfcOrderList.size.small'),
      value: 'small',
    },
    {
      name: t('nfcOrderList.size.medium'),
      value: 'medium',
    },
    {
      name: t('nfcOrderList.size.large'),
      value: 'large',
    },
  ]);
  // 尺寸变化
  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined
  ) => {
    size.value = val as SizeProps;
  };
  // 拖拽排序

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };
  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }

  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }

  .setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
